<?php
/*
 * Created on May 12, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	class Pcategory extends VNT_Controller{
		function Pcategory(){
			parent::VNT_Controller();
			$this->load->library('xajax', 'category');
			//$this->xajax->registerFunction(array('setDisplay', &$this, 'setDisplay'));
			$this->xajax->registerFunction(array('changeBestSell', &$this, 'changeBestSell'));
            $this->xajax->registerFunction(array('changeSpecial', &$this, 'changeSpecial'));
            $this->xajax->registerFunction(array('changeDisplay', &$this, 'changeDisplay'));
			$this->xajax->processRequest();
			$this->xajax_js = $this->xajax->getJavascript($this->base_url.'js/');
			$this->load->model('pcategory_model', 'pcategory', true);
			$this->checkLogin();
			//$this->checkPermission();
		}

        function changeBestSell($id){
            $this->load->model('product_model', 'product', true);
            $this->load->model('pcategory_model', 'pcategory', true);

            $category = $this->pcategory->getById($id);

			if($category){

                $category->best_sell = $category->best_sell==1? 0 : 1;

                $this->pcategory->update($category);

                $this->pcategory->applyBestSellProduct($id, $category->best_sell);

                $objResponse = new xajaxResponse();

                //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

                return $objResponse;
			}
        }

        function changeSpecial($id){
            $this->load->model('product_model', 'product', true);
            $this->load->model('pcategory_model', 'pcategory', true);

            $category = $this->pcategory->getById($id);

			if($category){

                $category->special = $category->special==1? 0 : 1;

                $this->pcategory->update($category);

                $this->pcategory->applySpecialProduct($id, $category->special);

                $objResponse = new xajaxResponse();

                //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

                return $objResponse;
			}
        }

        function changeDisplay($id){
           $this->load->model('product_model', 'product', true);
            $this->load->model('pcategory_model', 'pcategory', true);

            $category = $this->pcategory->getById($id);

			if($category){

                $category->active = $category->active==1? 0 : 1;

                $this->pcategory->update($category);

                $objResponse = new xajaxResponse();

                //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

                return $objResponse;
			}
        }
        
		function index(){
			$this->view();
		}
		
		function parseWhere($paremeters){
			$result = '';
			//if()
			$operation = '';
			
			foreach($paremeters as $para => $value){
				if($para == 'AND'){
					$operation = 'AND';
					$index = 1;
					$num = count($value);
					$result .= ' (';
					foreach($value as $p => $v){
						if($p=='AND' OR $p=='OR'){
							$result .=  $this->parseWhere($v) ;
							//print_r($v);
							//echo '<br>Nhanh con:...' . $this->parseWhere($value) . '...<br>';
							//echo 'Goi de quy.';
						}
						else{ echo '<br> Goi phan d=> 12 <br>';
							$result .= $p . '=' . $v;
						}
						
						if($index < $num)
							$result .=  ' AND ';
													
						$index++;
					}
					$result .= ' )';
				}
				if($para == 'OR'){
					$operation = 'OR';
					$index = 1;
					$num = count($value);
					$result .= ' (';
					foreach($value as $p => $v){
						if($p=='AND' OR $p=='OR'){
							$result .=  $this->parseWhere($value) ;
							//print_r($v);
							//echo '<br>Nhanh con:...' . $this->parseWhere($value) . '...<br>';
							//echo 'Goi de quy.';
						}
						else{
							$result .= $p . '=' . $v;
						}
						
						if($index < $num)
							$result .=  ' OR ';
													
						$index++;
					}
					$result .= ' )';
				}
				
			}
			
			return $result;
		}
		
		function create(){
			$obj = new stdClass();
			$obj->id_pcategory = 0;
			$obj->id_parent_pcategory = 0;
			$obj->vi_name = '';
			$obj->en_name = '';
			$obj->vi_description = '';
			$obj->en_description = '';
			$obj->number_product = 0;
			$obj->link_rewrite = '';
			$obj->meta_title = '';
			$obj->meta_keywords = '';
			$obj->meta_description = '';
			$obj->level_depth = 0;
			$obj->active = 1;
			$obj->module = PRODUCTS_PAGE;
			$obj->date_add = date('Y-m-d H:i:s', time());
			$obj->date_upd = date('Y-m-d H:i:s', time());
						
			$obj->code = ''; 
			$obj->code_parent = '';
								
			
			$data = array();
			$data['category'] = $obj;
			$data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', '');
			$data['error_message'] = '';
			$data['legend_text'] = lang('create_product_category');
			$this->main = $this->load->view('admin/pcategory/create_pcategory', $data, true);
			$this->execute();
		}
		
		function setDisplay($id){
			$this->load->model('pcategory_model', 'pcategory', true);
			$category = $this->pcategory->getById($id);
			
			if($category){
				$category->active = $category->active==1? 0 : 1;

                $this->category->update($category);

                $objResponse = new xajaxResponse();

                //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

                return $objResponse;
			}
			
		}
		
		function edit($id){
			$category = $this->pcategory->getById($id);
			
			if(!$category){
				redirect('pcategory/view');
			}
			
			$data = array();
			$data['category'] = $category;
			$data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $category->code_parent);
			$data['error_message'] = '';
			$data['legend_text'] = lang('edit_product_category');
			$this->main = $this->load->view('admin/pcategory/create_pcategory', $data, true);
			$this->execute();
		}
		
		function create_from_file(){ //   
			$error_message = ''; 
			if(isset($_FILES['file']['tmp_name'])){
				$config['upload_path'] = './Data/';
				$config['allowed_types'] = 'xls';
				//$config['overwrite'] = true; 
				$config['max_size']	= 8192; // 8192 kb = 8mb
				//$config['max_width']  = '1024';
				//$config['max_height']  = '768';
				//$config['max_filename'] = 50; 
				//$config['encrypt_name'] = true; 
				//$config['remove_spaces'] = false; 
				$result_upload = $this->uploadFile($config);
				if($result_upload['error']){
						
					$error_message = $result_upload['message']; 
				}
				else{
					
					//if($result_upload['upload_data']['file_type']==)
					//echo $config['upload_path'].$result_upload['upload_data']['file_name'];
					//echo mime_content_type($config['upload_path'].$result_upload['upload_data']['file_name']);
					
					$this->load->library('excel/spreadsheet_Excel_Reader');
							
					$data = new Spreadsheet_Excel_Reader();
			    
					$data->setOutputEncoding('utf-8');
					//$data->setOutputEncoding('windows-1258');
					//$data->setOutputEncoding('iso-8859-1');
				
			   		$data->read($config['upload_path'].$result_upload['upload_data']['file_name']);
					if(!isset($data->_ole->error)){
						//$data->read('BG MBT 1P 4-2009.xls');
						//$data->sheets[1]['cells'][2][3];
						//$data->sheets[SHEET]['cells'][ROW][COLUMN];
				//print_r($data);
						error_reporting(E_ALL ^ E_NOTICE);
						//$colspan = 1;
						//echo "Sheet:".count($data->sheets);
						//echo "Sheet:".$data->sheets[0]['numCols'];
						$objects = array();
						for($a = 0; $a < count($data->sheets); $a++){
							//echo 'TEn sheet:' . $data->boundsheets[$a]['name'];
							for ($i = 2; $i <= $data->sheets[$a]['numRows']; $i++) {
								//if($data->sheets[$a]['numCols'] < 3) break;
								//echo "<br>Row:".$data->sheets[$a]['cellsInfo'][1] .'_'. $i;
								$obj = new stdClass();
								$obj->id_parent_pcategory = 0;
								//$obj->vi_name = '';
								//$obj->en_name = '';
								$obj->vi_description = '';
								$obj->en_description = '';
								$obj->number_product = 0;
								$obj->link_rewrite = '';
								$obj->meta_title = '';
								$obj->meta_keywords = '';
								$obj->meta_description = '';
								$obj->level_depth = 0;
								$obj->active = 1;
								$obj->module = PRODUCTS_PAGE;
								$obj->date_add = date('Y-m-d H:i:s', time());
								$obj->date_upd = date('Y-m-d H:i:s', time());
						
								$obj->code = trim($data->sheets[$a]['cells'][$i][1]); 
								$obj->code_parent = trim($data->sheets[$a]['cells'][$i][2]);
								$obj->vi_name = trim($data->sheets[$a]['cells'][$i][3]); 
								$obj->en_name = trim($data->sheets[$a]['cells'][$i][3]); 
								if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
									$objects[] = $obj;
								//	break;
								//if($obj->code!='' AND $obj->vi_name!='')
								//$objects[] = $obj;
								
								/*
								for ($j = 1; $j <= $data->sheets[$a]['numCols']; $j++) {
									$value = $data->sheets[$a]['cells'][$i][$j];
									$colspan = $data->sheets[$a]['cellsInfo'][$i][$j]['colspan'];
									if($colspan){
										//echo "<td colspan='$colspan' style='border-bottom:1px solid black;'>". $value . "</td>\n";
									}
									else{
										if(!$value) $value = "&nbsp;";
										//echo "<td style='border-bottom:1px solid black;'>". $value . "</td>\n";
										$colspan = 1;
									}
								
								} // for column		
								*/		
							
							} //for row
						} // for count sheet
						if(count($objects)>0){
							$result = $this->pcategory->create($objects);
							if($result){
								$this->pcategory->updateParentId();
							}
							@unlink($config['upload_path'].$result_upload['upload_data']['file_name']);
							//redirect('admin/pcategory');	
							//return;
						}
						
					} //if
					else{
						$error_message .= 'The filename ' . $result_upload['upload_data']['file_name'] . ' is not readable';
					}
			
				}
			}
			$data = array();
			$data['error_message'] = '<div style="color:red">'.$error_message . '</div>';
			$this->main = $this->load->view('admin/pcategory/form_upload', $data, true);
			$this->execute();
		}
		
		function upload_image($field_name, $path, $allowed_types = '')
		{
			$result = array();
			$config['upload_path'] = $path; //'./Data/Images/';
			if($allowed_types == '')
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
			else $config['allowed_types'] = $allowed_types;
			//$config['max_size']	= '1000';
			//$config['max_width']  = '1024';
			//$config['max_height']  = '768';
			$config['overwrite']  = false;
			
			
			$this->load->library('upload', $config);
		
			if (!$this->upload->do_upload($field_name))
			{
				//$error = array('error' => $this->upload->display_errors());
				$result['error'] = true;
				$result['message'] = $this->upload->display_errors();
				//$this->load->view('upload_form', $error);
			}	
			else
			{
				//$data = array('upload_data' => $this->upload->data());
				$result['error'] = false;
				$result['upload_data'] = $this->upload->data();
			}
			
			return $result;
		}	
		
		/*function uploadFile($config){
					
			$this->load->library('upload', $config);
			$result = array('error' => false);
		
			if ( ! $this->upload->do_upload('file'))
			{
				$result['message'] = $this->upload->display_errors();
				$result['error'] = true;
			}	
			else
			{
				$result['upload_data'] = $this->upload->data();
				
			}
			
			return  $result;
		}*/
		
		function view(){
			$this->load->library('pagination');
			
			$id_parent = intval($this->uri->segment(4));
			$_code_parent = $id_parent;
			$page = (int)$this->uri->segment(5);
			//if($code_parent=='') $_code_parent = '0';
			$base_url = $this->base_url . 'admin/pcategory/view/' . $id_parent. '/';
			
			//if($id_parent=='_') $id_parent = '';
			
			$parameters = array();
			
			$parameters['code_parent'] = $id_parent;
			//$parameters[' AND code'] = ' "MAYLANH';
			
			//$total_rows = $this->pcategory->countAll($code_parent);
			$total_rows = $this->pcategory->countAllAdmin($id_parent);
			
			$per_page = NUMBER_RECORD_PER_CATEGORY_PAGE;
			
			$uri_segment = 5;
						
			//$this->pagination->initialize($config);
			
			pagination($base_url, $total_rows, $per_page , $uri_segment);
			
			//$paging = $this->pagination->create_links();
			
			//$this->setTemplate(array ('admin/pcategory/pcategory_list.tpl'));
			//$items = $this->loadItems();
			//$items = '';
			//$pcategories = $this->pcategory->getAllByCode($code_parent, NUMBER_RECORD_PER_PAGE, $page);
			
						
			$pcategories = $this->pcategory->getAllAdmin($page, $per_page, $id_parent);
			
            
			if($page > 0 AND count($pcategories)==0){
				redirect('admin/pcategory/view/' . ($page-$per_page));
				return;
			}
			
			$track = getTrack($id_parent, null, $lang = 'vi' );
			
			$data = array();
			$data['rows'] = $pcategories;
			$data['track'] = $track;
			//$this->main = eval ($this->loadTemplate('admin/product/product_list.tpl'));
			$this->main = $this->load->view('admin/pcategory/pcategory_list', $data, true);
			
			//$this->main = eval ($this->loadTemplate('admin/pcategory/pcategory_list.tpl'));
			$this->execute();
		}
		
		function view_tree(){
			//$this->load->model('pcategory_model', 'category', true);
			$categories = $this->pcategory->getAll(); 
			$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
			$space = '';
			//$name = 'Parent';
			$value = '';
			$selected = '';
			$space= '';
			$label = 'Parent';
			$class = '';
			$action = '';
			$style = '';
			
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				//$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
				$tmp[$category->code_parent][$category->code] = $category;
			}
						
			//$rows = $this->help_view_tree($tmp, $parent = '', $space = '&nbsp;');
            $rows = $this->help_view_tree($tmp, $parent = '', $space = '::');
			$data = array();
			$data['rows'] = $rows;
			
			$this->main = $this->load->view('admin/pcategory/pcategory_tree', $data, true);
			
			$this->execute();
			
		}
		
		function help_view_tree($tmp/*$categories*/, $parent = ''/*0*/, $space = ''){
			$items = '';
			$result = array();
			if(isset($tmp[$parent])){  
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){ 
					$parent = $v->code;
					$value = $v->code;
					$label = $v->vi_name;
					$selected = '';
					$v->vi_name = $space . $v->vi_name;
					//$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
					$result[] = $v;
					//$items .=$this->help_view_tree($tmp/*$categories*/ , $parent, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
					//$result = array_merge($result, $this->help_view_tree($tmp/*$categories*/ , $parent, $space . '|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'));
                    $result = array_merge($result, $this->help_view_tree($tmp/*$categories*/ , $parent, $space . '|-------'));
				}
			}
			
			return $result;
		
		}
		
		function loadItems(){
			/*$item = '';
			$items = $this->pcategory->getAll();
			$this->setTemplate(array ('admin/pcategory/pcategory_item.tpl'));
			for($i = 0; $i < count($items); $i++){
				$id = $items[$i]->id_pcategory;
				$name = $items[$i]->vi_name;
				$description = $items[$i]->vi_description;
				$item .= eval ($this->loadTemplate('admin/pcategory/pcategory_item.tpl'));
			}
			
			return $item;*/
		}	
		
		
		function edit_news_category($id){
		
			$this->setTemplate('edit_news_category.tpl');
			$code = uniqid();
			$this->session->set_userdata('code', $code);
			$this->load->model('news_category_model', 'category', true);
			$category = $this->category->getById($id);
			
			if(!$category){
				redirect('category/view_news_category');
			}
			
			$txtID = $category->category_id;
			$txtNameVi = $category->name_vi;
			$txtNameEn = $category->name_en;
			$txtDescriptionVi = $category->description_vi;
			$txtDescriptionEn = $category->description_en;
			$cbActive = $category->active == 1 ? 'checked' : '';
			$error_message = '';
			$picture = $category->picture == "" ? "" : "<img src='".$this->base_url."data/categories/news/{$category->picture}' width=150 height=50";
			$category_parent = $this->buidDDProductCategoryList('ddlParentCategory', $category->category_parent_id);
			$content = eval($this->loadTemplate('edit_news_category.tpl'));
			$this->execute($content);
		}
		
		function view_news_category(){
		
			$this->load->model('news_category_model', 'category', true);
			$categories = $this->category->getAll();
			
			$this->setTemplate(array('news_categories.tpl', 'news_categories_item.tpl'));
			$items = $this->loadNewsItems($categories);
			$content = eval($this->loadTemplate('news_categories.tpl'));
			$this->execute($content);
		}
		
		function loadNewsItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
			$items = '';
			if(!$categories){
				$categories = $this->category->getAll();
			}
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				$tmp[$category->category_parent_id][$category->category_id] = $category;
			}
			
			
			if(isset($tmp[$parent])){
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){
					$parent = $v->category_id;
					$category_id = $v->category_id;
					$category_name = $v->name_vi;
					if($index%2 == 0) $class = 'class="bg"';
					else $class = '';
					$items .= eval($this->loadTemplate('news_categories_item.tpl'));
					//if(in_array($v->category_id, $track))
					$index++;
					$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
				}
				
				/*for($j = 1; $j <= count($tmp[$parent]); $j++){
					if(isset($tmp[$parent][$j])){
						$category = $tmp[$parent][$j]; 
						$parent = $category->category_id;
						$category_id = $category->category_id;
						$category_name = $category->name;
						if($index%2 == 0) $class = 'class="bg"';
						else $class = '';
						$items .= eval($this->loadTemplate('product_categories_item.tpl'));
						//if(in_array($v->category_id, $track))
						$index++;
						$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
					}
				}*/
			}
			//print_r($categories);
			return $items;
		}
		
		function view_product_category(){
			$this->load->model('product_category_model', 'category', true);
			$categories = $this->category->getAll();
			$items = $this->loadProductItems($categories);
			$content = eval($this->loadTemplate('product_categories.tpl'));
			$this->execute($content);
		}
		
		function loadProductItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
			$items = '';
			if(!$categories){
				$categories = $this->category->getAll();
			}
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				$tmp[$category->category_parent_id][$category->category_id] = $category;
			}
			
			
			if(isset($tmp[$parent])){
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){
					$parent = $v->category_id;
					$category_id = $v->category_id;
					$category_name = $v->name_vi;
					if($index%2 == 0) $class = 'class="bg"';
					else $class = '';
					$items .= eval($this->loadTemplate('product_categories_item.tpl'));
					//if(in_array($v->category_id, $track))
					$index++;
					$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
				}
				
				/*for($j = 1; $j <= count($tmp[$parent]); $j++){
					if(isset($tmp[$parent][$j])){
						$category = $tmp[$parent][$j]; 
						$parent = $category->category_id;
						$category_id = $category->category_id;
						$category_name = $category->name;
						if($index%2 == 0) $class = 'class="bg"';
						else $class = '';
						$items .= eval($this->loadTemplate('product_categories_item.tpl'));
						//if(in_array($v->category_id, $track))
						$index++;
						$items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
					}
				}*/
			}
			//print_r($categories);
			return $items;
		}
		
		function buidDDProductCategoryList($name, $default){
			//$this->load->model('pcategory_model', 'category', true);
			$categories = $this->pcategory->getAll(); 
			$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
			$space = '';
			//$name = 'Parent';
			$value = '';
			$selected = '';
			$space= '';
			$label = 'Parent';
			$class = '';
			$action = '';
			$style = '';
			
			$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				//$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
				$tmp[$category->code_parent][$category->code] = $category;
			}
			
			$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
			return eval($this->loadTemplate('admin/ddl.tpl'));
		}
		
		function buidDDNewsCategoryList($name, $default){
			$this->load->model('news_category_model', 'category', true);
			$categories = $this->category->getAll();
			$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
			$space = '';
			$name = 'Parent';
			$value = 0;
			$selected = '';
			$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($categories, 0, $default);
			return eval($this->loadTemplate('admin/ddl.tpl'));
		}
		
		function getCategoryOption($tmp/*$categories*/, $parent = ''/*0*/, $default = ''/*0*/, $space = '&nbsp;'){
			$items = '';
			/*if(!$categories){
				$categories = $this->pcategory->getAll();
			}*/
			/*$tmp = array();
			for($i = 0; $i <count($categories); $i++){
				$category = $categories[$i];
				//$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
				$tmp[$category->code_parent][$category->code] = $category;
			}*/
			//print_r($tmp);		
			if(isset($tmp[$parent])){  
				$num_record = count($tmp[$parent]);
				foreach($tmp[$parent] as $k => $v){ 
					//$parent = $v->id_pcategory;
					//$value = $v->id_pcategory;
					//echo '<br>\n'.$parent . '_\n';
					$parent = $v->code;
					$value = $v->code;
					$label = $v->vi_name;
					$selected = '';
					if($value == $default) $selected = 'selected';
					$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
					
					$items .=$this->getCategoryOption($tmp/*$categories*/ , $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
				}
			}
			
			return $items;
		}
		
		function test(){
            $email_address = "sd_sd@ere.re-hggh,rr";
           /* $result = ereg("/^[A-Z]+$/", $email_address);
             if($result)
            {
                echo "Khong hop le: " . $email_address . "<br>";
            }
            else
                echo "Hop le: " . $email_address . "<br>";
           //echo "<br>" . time();
           */
           echo  eregi('[^a-z0-9_@,;.-]', $email_address) ? 'Invalid' : 'Valid';
        }
		function save(){
			//$this->setTemplate('form_new_ncategory.tpl');
			$txtID = (int)trim($this->input->post('txtID'));
			$txtCode =  /*preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode')));*/ trim($this->input->post('txtCode'));
			$txtLinkRewrite = trim($this->input->post('txtLinkRewrite'));
			
			if($txtID > 0)
			$category = $this->pcategory->getById($txtID);	
			else{
				$category = new stdClass();
				$category->id_pcategory = 0;	
				$category->code = '';
                $category->image = '';
				//$category->code_parent = '';	
			} 
			
			$this->load->helper(array('form', 'url'));
		
			$this->load->library('form_validation');
			
			if(($txtCode!=$category->code AND $txtID > 0) OR $txtID==0){
		   	 $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]|callback_code_check|callback_code_validate_check');
		   	 //echo $txtCode.' '.$category->code; return;
			}else
		    $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]|callback_code_validate_check');
		    //$this->form_validation->set_rules('parent', 'lang:parent_code', 'required|min_length[2]|max_length[120]');
			$this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
			$this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
			if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category->link_rewrite)
			$this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
			/*$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
			$this->form_validation->set_rules('email', 'Email', 'required');
			*/	
						
			if(!$category AND $txtID > 0){
				redirect('addmin/pcategory/view');
				return;
			}
					
			$category->code = /*preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode')));*/ trim($this->input->post('txtCode'));
			$category->code_parent = trim($this->input->post('parent'));
			$category->vi_name = trim($this->input->post('txtViName'));
			$category->en_name = trim($this->input->post('txtEnName'));
			$category->vi_description = trim($this->input->post('txtViDescription'));
			$category->en_description = trim($this->input->post('txtEnDescription'));
			$category->meta_description = trim($this->input->post('txtMetaDescription'));
			$category->link_rewrite = trim($this->input->post('txtLinkRewrite'));
			$category->meta_title = trim($this->input->post('txtMetaTitle'));
			$category->meta_keywords = trim($this->input->post('txtMetaKeywords'));
			$category->active = (int)$this->input->post('active');
			$category->module = trim($this->input->post('module'));
			$category->date_upd = date('Y-m-d H:i:s', time());
			$error_message =''; // $this->loadErrorMessage('Thong diep loi.');
			$category_parent = ''; //$this->buidDDNewsCategoryList('ddlParentCategory', 0);
			
			$attach_image = false;
			$image_upload = array('error'=> false);
			if(isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0){  
				$attach_image = true;
				$image_upload = $this->upload_image('file', CATEGORY_IMAGE_PATH /*'./Data/Images/Product/'*/);
				if($image_upload['error'])
					$error_message .= $image_upload['message'];
				
			}
			
			if ($this->form_validation->run() == FALSE OR ($attach_image == true AND $image_upload['error']==true)){
				//$code = uniqid();
				//$this->session->set_userdata('code', $code);
				$error_message = validation_errors(). '<br>'. $error_message;
				$data = array();
				$data['category'] = $category;
				$data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $category->code_parent);
				$data['error_message'] = '<div style="color:red">' . $error_message.'</div>';
				//if()
				$data['legend_text'] = $txtID>0 ?  lang('edit_product_category') : lang('create_product_category');
				$this->main = $this->load->view('admin/pcategory/create_pcategory', $data, true);
				$this->execute();
				return;
			}
			else{
				if($attach_image){
					$file_path = CATEGORY_IMAGE_PATH . $image_upload['upload_data']['file_name'];
					if($txtID > 0 AND $category->image!=$file_path) { 
						@unlink($category->image);
					}
					
					$category->image = $file_path;
				}

                if($category->code_parent!=""){
                    $parent_cat = $this->pcategory->getByCode($category->code_parent);
                    $category->id_parent_pcategory = $parent_cat->id_pcategory;
                }
                else $category->id_parent_pcategory = 0;
                
				if($txtID > 0){
					$result = $this->pcategory->update($category);
				}
				else{
					$category->number_product = 0;
					$category->level_depth = 0;
					$category->date_add = date('Y-m-d H:i:s', time());
					$result = $this->pcategory->create($category);
					
				}
					
				//redirect('admin/pcategory/view');
                redirect($_SESSION["his_adm"]);
			}
			
		}
		
		function code_check($code){ 
			$result = $this->pcategory->getByCode($code); 
			if ($result!=null){ 
				$this->form_validation->set_message('code_check', '%s is not available.');
				return FALSE;
			}
			else{
				return TRUE;
			}
		}

        function code_validate_check($code){
            if(eregi('[^a-z0-9_@,.-]', $code)){
                //? 'Invalid' : 'Valid';
                $this->form_validation->set_message('code_validate_check', '%s is invalid.');
				return FALSE;
            }
            else{
                return TRUE;
            }
        }
		
		function friendly_url_check($url){
			$result = $this->pcategory->getByLinkRewrite($url);
			if ($result!=null){ 
				$this->form_validation->set_message('friendly_url_check', '%s is not available.');
				return FALSE;
			}
			else{
				return TRUE;
			}
		}
		
		function testGetFile(){
 		$config = array(
 			'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
 			'max_size'=> 1024000000 /*1Mb*/
 		);
 		
 		 $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');
 		 
 		 if(!$result['error']) echo 'Get file success.';
 		 else echo $result['message'];
 		 
 	}
 	
 	function delete(){
 		$id = intval($this->uri->segment(4));
 		if($id>0)
 			$this->pcategory->delete($id);
 		else{
 			if(($this->input->post('submitDelcategory'))){
 				$ids = $this->input->post('categoryBox');
 			 	if(count($ids))
 			 		$this->pcategory->delete($ids);
 			}
 		}
 		//redirect('admin/pcategory');
        redirect($_SESSION["his_adm"]);
 	}
	
	function change_order(){
		$id1 = (int)$this->uri->segment(4);
		$id2 = (int)$this->uri->segment(5);
		
		$cat1 = $this->pcategory->getById($id1);
		$cat2 = $this->pcategory->getById($id2);
		
		if($cat1 AND $cat2){
			$position1 = $cat1->order_view;
			$cat1->order_view = $cat2->order_view;
			$cat2->order_view = $position1;
			
			$this->pcategory->update($cat1);
			$this->pcategory->update($cat2);
			
		}
		
		redirect($_SESSION['his_adm']);
	}
 	
	}
?>
